package com.module.third;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TemporaryData {
    private volatile static TemporaryData instance;
    private Map<String, Object> cacheData = new ConcurrentHashMap();

    private static TemporaryData getInstance() {
        if (instance == null) {
            synchronized (TemporaryData.class) {
                if (instance == null) {
                    instance = new TemporaryData();
                }
            }
        }
        return instance;
    }

    public static void put(String key, Object data) {
        getInstance().cacheData.put(key, data);

    }

    /**
     * 取出数据，不会删除数据
     */
    public static <T> T get(String key, Class<T> classOfT) {
        Object object = getInstance().cacheData.get(key);
        if (classOfT == Boolean.class) {
            object = object == null ? false : object;
        } else if (classOfT == Integer.class) {
            object = object == null ? 0 : object;
        } else if (classOfT == Long.class) {
            object = object == null ? 0L : object;
        } else if (classOfT == Float.class) {
            object = object == null ? 0F : object;
        } else if (classOfT == Double.class) {
            object = object == null ? 0D : object;
        }
        return (T) object;
    }

    /**
     * 取出数据，该数据马上会被清空
     */
    public static <T> T getTemporary(String key, Class<T> classOfT) {
        T t = get(key, classOfT);
        getInstance().cacheData.remove(key);
        return t;
    }


    public static void clear() {
        if (getInstance() == null || getInstance().cacheData == null) {
            return;
        }
        getInstance().cacheData.clear();
    }
}
